<?php
/**
 * Created by PhpStorm.
 * User: wuxiang
 * Date: 2016/9/6
 * Time: 13:52
 */

namespace Common\Libiary;

/**
 * Class WechatMaterial
 * @package Common\Libiary
 * 获取微信永久素材
 */

class WechatMaterial
{

    private $url;
    private $data;
    private $list;
    private $tagsRes = [];
    private $secretusernew = ')*&(^%$@!mwbyd';

    private $secret = '**9noww!@mwbyd&&';

    //获取标签方法和总数
    function getTagsList()
    {

        //城市标签接口
        $list = $this->getCity();

        foreach ($list as $k => $v) {

            $rest[] = $v['id'];
        }

        $arr = implode(',', $rest);

        //获取粉丝数
        $rest = $this->getTotal($arr);
        //组合数组
        foreach ($list as $item => $row) {
            $list[$item]['id'] = $row['id'];
            $list[$item]['city'] = $row['id'];
            $list[$item]['name'] = $row['name'];
            $list[$item]['total'] = $this->getCityTotal($row['id'],$rest);

        }

        LogEX::i('获取城市标签结果集', ['data' => $list], __FILE__, __LINE__);

        return $list;

    }

    function getCityTotal($cityId,$rest)
    {
        if(!$rest){
            return 0;
        }
        foreach($rest as $k=>$v){
            if($v['city']==$cityId){
                $total = isset($v['total'])&&$v['total'] ? $v['total'] : 0;
            }
        }
        return $total;
    }

    //获取城市
    function getCity()
    {

        $this->url = 'http://usernew.mwee.cn/index.php?s=/Api/Api';
        if (TP_DEBUG) $this->url = 'http://usernew.st.9now.net/index.php?s=/Api/Api';

        LogEX::i('获取TP_DEBUG', ['data' => TP_DEBUG], __FILE__, __LINE__);

        $this->data['action'] = 'push.getPushTagList';
        $this->data['s'] = '/Api/Api';
        $this->data['data'] = json_encode(['tagType' => 1]);

        $baseApi = new BaseApiHttp();
        $params = $baseApi->createSignCode($this->secret);

        $info = array_merge($this->data, $params);

        LogEX::i('获取城市标签', $info, __FILE__, __LINE__);
        $ret = $baseApi->http($this->url, 'POST', $info);
        LogEX::i('获取城市标签数据', ['data' => $ret], __FILE__, __LINE__);
        $this->list = json_decode($ret, true);

        return $this->list['data']['data'];

    }

    //获取收益粉丝数
    function getTotal($arr)
    {
        $this->res['action'] = 'push.getUserTagPushOpenIdCount';
        $this->res['s'] = '/Api/Api';
        $this->res['data'] = json_encode(['city' => $arr,'tags'=>'美味不用等']);

        LogEX::i('获取城市粉丝数据2', ['data' => $this->res], __FILE__, __LINE__);
        $baseApi = new BaseApiHttp();
        $paramsInfo = $baseApi->createSignCode($this->secret);

        $mergeInfo = array_merge($this->res, $paramsInfo);

        $setUrl = 'http://usernew.mwee.cn/index.php?s=/Api/Api';
        if (TP_DEBUG) $setUrl = 'http://usernew.st.9now.net/index.php?s=/Api/Api';
        $rets = $baseApi->http($setUrl, 'POST', $mergeInfo);
        LogEX::i('获取城市粉丝数据', ['data' => $rets], __FILE__, __LINE__);
        $rest = json_decode($rets, true);
        LogEX::i('获取城市粉丝数据1', ['data' => $rest], __FILE__, __LINE__);
        return $rest['data'];
    }

    //获取粉丝列表
    function getFansList($arr,$tryTimes = 1, $timeout = 25)
    {
        $this->res['action'] = 'push.getUserTagPushOpenIdList';
        $this->res['s'] = '/Api/Api';
        $this->res['data'] = json_encode($arr);
        LogEX::i('获取粉丝信息2', ['data' => $this->res], __FILE__, __LINE__);
        $baseApi = new BaseApiHttp();
        $baseApi->timeout = $timeout;
        $paramsInfo = $baseApi->createSignCode($this->secret);
        $mergeInfo = array_merge($this->res, $paramsInfo);
        $setUrl = 'http://usernew.mwee.cn/index.php?s=/Api/Api';
        if (TP_DEBUG) $setUrl = 'http://usernew.st.9now.net/index.php?s=/Api/Api';
        $rets = $baseApi->http($setUrl, 'POST', $mergeInfo);
        LogEX::i('获取粉丝信息', ['data' => $mergeInfo, 'url' => $setUrl, 'res' => $rets], __FILE__, __LINE__);
        $ret = json_decode($rets, true);
        if(empty($ret)) LogEX::i('获取粉丝信息失败', ['data' => $mergeInfo, 'url' => $setUrl, 'res' => $rets,'retryTimes'=>$tryTimes], __FILE__, __LINE__);
        return $ret['data'];
        /**
         * if(empty($ret['data']) && $tryTimes < 5){
            LogEX::i('获取粉丝信息失败', ['data' => $mergeInfo, 'url' => $setUrl, 'res' => $rets,'retryTimes'=>$tryTimes], __FILE__, __LINE__);
            $timeout = 25 + 5*$tryTimes;
            return $this->getFansList($arr,$tryTimes+1,$timeout);
        }else{
            return $ret['data'];
        }
         * */
    }

    function getToken()
    {

        $tokenData = $this->getAccessToken();

        LogEX::i('获取token信息', ['data' => $tokenData], __FILE__, __LINE__);
        //解密
        $accessTokenInfo = $this->decryptAccessToken($tokenData['access_token']);

        LogEX::i('获取token解密', ['data' => $accessTokenInfo], __FILE__, __LINE__);

        return $accessTokenInfo;

    }


    /**
     * 获取access_token
     */

    function getAccessToken()
    {

        $this->url = 'http://wx.mwee.cn/WxOath/AccessToken/wxtoken';
        if (TP_DEBUG) $this->url = 'http://jaq.9now.net/WxOath/AccessToken/wxtoken';
        $baseApi = new BaseApiHttp();
        $this->data = $baseApi->createSignCode($this->secretusernew);
        $ret = $baseApi->https($this->url, 'POST', $this->data);
        LogEX::i('获取token信息', ['data' => $ret], __FILE__, __LINE__);
        $this->list = json_decode($ret, true);

        if ($this->list['errno'] == 0) {
            return $this->list['data'];
        } else {
            return false;
        }

    }

    /**
     * @param $access_token
     * @return mixed
     * 解密
     */
    function decryptAccessToken($access_token)
    {
        $aes = new CryptAES();
        $aes->set_key($this->secretusernew);
        $aes->require_pkcs5();
        // $encText = $aes->encrypt($access_token);  //加密
        $decString = $aes->decrypt($access_token);  //解密

        LogEX::i('获取解密token信息', ['data' => $decString], __FILE__, __LINE__);
        return $decString;
    }

    /*
        *获取文章数量
        */
    public function get_article_count($access_token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=" . $access_token;
        $response = file_get_contents($url);
        $res = json_decode($response, true);

        LogEX::i('获取获取文章数量', ['data' => $res], __FILE__, __LINE__);
        return $res;
    }

    /*
    *获取文章列表
    *type 素材的类型:图片（image）、视频（video）、语音 （voice）、图文（news）
    *offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
    *count 返回素材的数量，取值在1到20之间
    */
    public function get_article_list($type, $offset, $count, $access_token)
    {

        $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" . $access_token;

        $data['type'] = $type;
        $data['offset'] = $offset;
        $data['count'] = $count;

        $arr = json_encode($data);
        //返回的数据
        $response = $this->get_response_post($url, $arr);
        $res = json_decode($response, true);
        return $res;
    }

    /**
     * @param $mediaId
     * @param $access_token
     * @return mixed
     */

    function getThumbInfo($mediaId, $access_token)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=' . $access_token;
        $arr = json_encode(['media_id' => $mediaId]);
        $response = $this->get_response_post($url, $arr);
        $res = json_decode($response, true);
        return $res;

    }

    /**
     * @param $url
     * @param $data
     * @return mixed
     * curl
     */

    public function get_response_post($url, $data)
    {
        $curl = curl_init($url);
        //curl_setopt($curl, CURLOPT_HEADER, 0);//过滤头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// post传输数据
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $responseText = curl_exec($curl);
        curl_close($curl);
        return $responseText;
    }

    /**
     * 图文入库
     * @param $type
     * @param $list
     * @return array
     */
    function import_opearte($type, $list)
    {
        $rest = [];
        foreach ($list as $k => $v) {
            $rest[$k]['media_id'] = $v['media_id'];

            if ($type == 'news') {
                $rest[$k]['item'] = json_encode($v['content']);
                $rest[$k]['meta_add_time'] = $v['content']['create_time'];
            } else {
                $rest[$k]['item'] = json_encode(['url' => $v['url'], 'name' => $v['name']]);
                $rest[$k]['meta_add_time'] = $v['update_time'];
            }
            $rest[$k]['update_time'] = $v['update_time'];
            $rest[$k]['type'] = $type;
            $rest[$k]['add_time'] = time();
        }

        LogEX::i('图文入库', ['data' => $rest], __FILE__, __LINE__);
        return $rest;
    }




//    /**
//     * 图文入库
//     * @param $type
//     * @param $list
//     * @return array
//     */
//    function import_opearte($type,$list)
//    {
//        $rest = [];
//        foreach($list as $k=>$v){
//            $rest[$k]['media_id'] = $v['media_id'];
//            $rest[$k]['item'] = json_encode($v['content']);
//            $rest[$k]['update_time'] =  $v['update_time'];
//            $rest[$k]['meta_add_time'] = $v['content']['create_time'];
//            $rest[$k]['type'] = $type;
//            $rest[$k]['add_time'] = time();
//        }
//        return $rest;
//    }
//
//    function handleImage($type,$list){
//        $result = [];
//        //素材入库
//        foreach($list as $k=>$v){
//            $result[$k]['media_id'] = $v['media_id'];
//            $result[$k]['update_time'] = $v['update_time'];
//            $result[$k]['item'] =  json_encode(['url'=>$v['url'],['name']=>$v['name']]);
//            $result[$k]['type'] = $type;
//            $result[$k]['add_time'] = time();
//        }
//        return $result;
//    }

    //获取推送事件结果
    function getFansIsSuccess($msg_id, $accessTokenInfo)
    {
        $msg = json_encode(['msg_id' => $msg_id]);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token=' . $accessTokenInfo;
        $response = $this->get_response_post($url, $msg);
        $res = json_decode($response, true);
        return $res;

    }


    //预览接口
    function viewInfo($openid, $type, $media_id, $access_token)
    {

        LogEX::i('预览接口2', ['data' => $openid, 'data1' => $type, 'data2' => $media_id, 'data3' => $access_token], __FILE__, __LINE__);

        $typeInfo = [
            [
                'news' => 'mpnews',
            ],
            [
                'image' => 'image',
            ],
            [
                'video' => 'video',
            ],
            [
                'voice' => 'voice',
            ]

        ];

        $typeCol = array_column($typeInfo, $type);
        LogEX::i('预览接口1', ['data' => $typeCol], __FILE__, __LINE__);

        $data = [];

        foreach ($openid as $k => $v) {
            $data[$k]['touser'] = $v;
            $data[$k][$typeCol[0]]['media_id'] = $media_id;
            $data[$k]['msgtype'] = $typeCol[0];
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=' . $access_token;

        foreach ($data as $k => $v) {
            $response = $this->get_response_post($url, json_encode($v));
            $res = json_decode($response, true);
        }
        LogEX::i('预览接口', ['data' => $res], __FILE__, __LINE__);

        return $res;
    }


    public function post($url, $data)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0);//过滤头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_POST, true); // post传输数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// post传输数据
        $responseText = curl_exec($curl);
        curl_close($curl);

        return $responseText;
    }

}